<template>
  <div>
    <div v-for="v in car" :key="v.id" style="display:flex;margin: 6px 0;">
        <van-checkbox v-model="v.isChecked"></van-checkbox>
        <div style="flex:1;overflow: hidden;">
          <van-card
            :price="v.price.toFixed(2)"
            :title="v.title"
            :thumb="v.urls[0]"
          >
            <!-- slot 内容分发 -->
            <template #num>
              <van-stepper
                v-model="v.count"
                integer
                @overlimit="overlimit(v.id)"
              />
            </template>
            <template #desc>
              <div class="van-ellipsis">
                {{ v.desc }}
              </div>
            </template>
          </van-card>
        </div>
    </div>
    <!--底部订单 -->
    <van-submit-bar
      :price="totalPrice"
      button-text="提交订单"
    >
      <van-checkbox v-model="totalCheck">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>


<script>
import { computed, ref, watch } from "vue";
import { Dialog } from "vant";
export default {
  name: "Car",
  setup() {
    // 数据
    const car = ref(JSON.parse(localStorage.getItem("car")) || []);

    // 计算属性
    const totalPrice = computed(() => {
      let price = 0;
      car.value.forEach(v => {
        // 验证是否选中
        if(v.isChecked) {
          price += v.count * v.price;
        }
      });
      return price * 100;
    });

    const totalCheck = computed({
      // 获取依赖的结果
      get() {
        return car.value.every(item => item.isChecked)
      },
      // 修改
      set(checked) {
        car.value.forEach(item => item.isChecked = checked)
      }
    });
    // 方法
    const overlimit = id => {
      Dialog.confirm({
        title: "警告",
        message: "确认要删除吗？"
      }).then(() => {
        // 点击了确认
        // 过滤id
        car.value = car.value.filter(item => item.id !== id);
        // 更新本地存储
        localStorage.setItem("car", JSON.stringify(car.value));
      });
    };

    // 侦听购物车数据的变化
    watch(car.value, () => {
      // 更新本地存储
      localStorage.setItem("car", JSON.stringify(car.value));
    });

    return {
      car,
      overlimit,
      totalPrice,
      totalCheck
    };
  },

};
</script>